package cn.kn.sys.service.impl;

import cn.kn.common.model.Constants;
import cn.kn.common.model.R;
import cn.kn.sys.dao.RecouresDao;
import cn.kn.sys.service.RecourcesService;
import cn.kn.sys.vo.MenuVo;
import cn.kn.sys.vo.NodeVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author WangJiang
 * @create 2020-12-09 10:12
 */
@Service
@RequiredArgsConstructor
public class RecouresServiceImpl extends BaseService implements RecourcesService {
    private final RecouresDao recouresDao;


    @Override
    public R<List<NodeVo>> prems() {
        return R.ok(recouresDao.getResources());
    }

    @Override
    public R<List<Long>> getResByRoleId(Long roleId) {
        return R.ok(recouresDao.getResByRoleId(roleId));
    }

    @Override
    public R<List<MenuVo>> menus() {
        List<MenuVo> menu = recouresDao.getMenu(getUserId());

        return R.ok(createMenus(menu,Constants.PID));
    }

    private  List<MenuVo>  createMenus(List<MenuVo> menu,Long pid) {
        return  menu.stream().filter(m -> m.getPid().equals(pid))
                .peek(m-> {
                    List<MenuVo> ms = createMenus(menu, m.getId());
                    if (!CollectionUtils.isEmpty(ms)) {
                        m.setChildren(ms);
                    }
                }).collect(Collectors.toList());
    }

}
